//
//  CustomInteractiveTransition.swift
//  taurus
//
//  Created by 刘艺 on 2021/8/16.
//  Copyright © 2021 com.fiture. All rights reserved.
//

import UIKit

class FitureCustomInteractiveTransition: UIPercentDrivenInteractiveTransition {
    var interacting = false
    var shouldComplete = false
    weak var presentedVC: FiturePresentContainerViewController?
    var config: FitureCustomPresentConfig = FitureCustomPresentConfig()

    func wireToViewController(viewController: FiturePresentContainerViewController,
                              config: FitureCustomPresentConfig = FitureCustomPresentConfig()) {
        self.config = config
        presentedVC = viewController
        prepareGestureRecognizerInView(view: viewController.view)
    }

    private func prepareGestureRecognizerInView(view: UIView) {

        let gesture = UIPanGestureRecognizer(target: self, action: #selector(handleGesture(gestureRecognizer:)))
        view.addGestureRecognizer(gesture)
    }

    @objc func handleGesture(gestureRecognizer: UIPanGestureRecognizer) {

        let translation = gestureRecognizer.translation(in: gestureRecognizer.view?.superview)

        switch gestureRecognizer.state {
        case .began:
            interacting = true
            presentedVC?.delegate?.willDismiss()
            presentedVC?.dismiss(animated: true, completion: {
                if self.shouldComplete {
                    self.presentedVC?.customInteractiveDismiss()
                }
            })
        case .changed:
            var fraction: CGFloat = 0.0
            if translation.y > 0 {
                fraction = translation.y / config.containerViewControllerHeight
                fraction = CGFloat(fminf(fmaxf(Float(fraction), 0.0), 1.0))
            }
            shouldComplete = (fraction > 0.5)
            self.update(fraction)
        case .ended, .cancelled:
            self.interacting = false
            if !self.shouldComplete || gestureRecognizer.state == .cancelled {
                self.cancel()
            } else {
                self.finish()
            }
        default:
            break
        }
    }
}
